package it.univaq.db.servlet;

import it.univaq.db.datamodel.Dbms_Manager;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Autenticazione
 */
@WebServlet(description = "Servlet che esegue l'autenticazione dell'utente",
	urlPatterns = { "/Autenticazione" })
public class Autenticazione extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    protected void processRequest(HttpServletRequest request, 
    		HttpServletResponse response) {
    	
    	String username = request.getParameter("username");
    	String password = request.getParameter("passwort");
    	
    	System.out.println("----------------------------------");
    	Enumeration parameters = request.getParameterNames();
        String param = null;
        // Iterate over the names, getting the parameters
        while ( parameters.hasMoreElements() )
        {
          param = (String)parameters.nextElement();
          System.out.println(" Parametro:" + param +" : " + request.getParameter(param));
        }
        
        System.out.println("User: " + username);
    	System.out.println("Pass: " + password);   
        System.out.println("----------------------------------");
    	
    	Dbms_Manager db = Dbms_Manager.getDataModel();
    	boolean autenticato = db.validazioneLogin(username, password);
    	
    	System.out.println("Autenticato: _> " + autenticato);
    	if(autenticato){
    		//Utente registrato e validato
    		try {
				response.sendRedirect("Menu.jsp");
			} catch (IOException e) {
				System.err.print("ERR 07 - Errore nel redirect positivo " +
						"del login");
			}
    	}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
